--[[
*名称:PurchaseLayer
*描述:支付界面
*版权:Copyright © 2016-2018 深圳市三只小熊科技有限公司 版权所有
*作者:管理员
*创建日期:
*修改日期:
*备注:该类属于baseClsss请勿修改，如需修改请详询管理员
]]
local PurchaseLayer = class("PurchaseLayer", PokerViewBase)
local CURRENT_MODULE_NAME = ...
--[[
界面处理需要保证就算是错误数据也做到不崩溃
在获取到数据的时候进行checkData操作
]]
function PurchaseLayer:onCreate()
    self:initWithFilePath("purchaselayer", CURRENT_MODULE_NAME)
    self:_initialize();
end
---
-- 初始化
-- @DateTime 2017-11-02
-- @return   [description]
--
function PurchaseLayer:_initialize()
    self._itemLayout = self.node.item_layout;
    self._listLayout = self.node.list_layout;
    self._listLayout:setItemModel(self._itemLayout);
    
    self._goodsList = self.node.lv_goods;
    self._goodsList:setItemModel(self._listLayout);
    self._goodsList:setScrollBarEnabled(false);
    
    self._btnClose = self.node.btn_close;
    self._btnClose:addClickEventListener(handler(self, self._onBtnCloseClicked));
end

---
-- 根据商品配置初始化商品列表
-- @DateTime 2017-11-02
-- @param    config [description]
-- @return    [description]
--
function PurchaseLayer:initConfig(config)
    local goodsData = {};
    local listItemData = {};
    for i, v in ipairs(config) do
        if #listItemData < 4 then 
            table.insert(listItemData, v);
        else 
            table.insert(goodsData, listItemData);
            listItemData = {};
            table.insert(listItemData, v);
        end
        
        if i == #config then 
            table.insert(goodsData, listItemData);
            listItemData = {};
        end
    end
    
    Log.d("PurchaseLayer:initConfig config: ", goodsData);
    
    for k, v in ipairs(goodsData or {}) do 
        self._goodsList:insertDefaultItem(k - 1);
        local listItem = self._goodsList:getItem(k - 1);
        for kk, vv in ipairs(v) do 
            listItem:insertDefaultItem(kk - 1);
            local goodsItem = listItem:getItem(kk - 1);
            local imgDiamond = goodsItem:getChildByName("img_diamond");
            local imgIndex = (k - 1) * 4 + kk;
            if imgIndex >= 7 then 
                imgIndex = 6;
            end
            imgDiamond:loadTexture(string.format(self.res_base .. "/img_diamond_%d.png", imgIndex, 0));
            
            local lblDiamondNum = goodsItem:getChildByName("lbl_diamond_num");
            lblDiamondNum:setString(vv.num);
            
            local btnBuy = goodsItem:getChildByName("btn_buy");
            local lblPrice = btnBuy:getChildByName("lbl_price");
            lblPrice:setString(vv.price);
            
            btnBuy:addClickEventListener(handler(self, function ()
                self:_onBtnBuyClicked(vv);
            end));
        end
    end
end

function PurchaseLayer:_onBtnBuyClicked(goodsInfo)
    Log.d("PurchaseLayer:_onBtnBuyClicked goodsInfo: ", goodsInfo);
    self.part:startPay(goodsInfo);
end

function PurchaseLayer:_onBtnCloseClicked()
    self.part:deactivate();
end

return PurchaseLayer